package com.itheima.interceptor;

import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    //控制器执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        log.info("preHandle方法执行了...");
        //1. 获取token
        String token = req.getHeader("token");

        //2. 如果token为空，直接返回401
        if (StringUtils.isEmpty(token)) {
            log.warn("请求头token为空");
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false; //拦截
        }
        //3. 解析token，如果解析失败 返回401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            log.info("校验通过，当前线程:{},当前登录用户id：{}",Thread.currentThread().getName(), id);
            //存入ThreadLocal中
            UserContext.setCurrentEmpId(Integer.parseInt(id.toString()));
        } catch (Exception e) {
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //4. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
